import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Link } from "react-router-dom";
import FormHead from "@/components/custom-ui/form-head";
import PasswordInput from "@/components/custom-ui/password-input";
import CaptchaInput from "@/components/custom-ui/captcha-input";
import { Mail } from "lucide-react";
import { useRouterQueryParam } from "@/hooks/use-query";
import { parseValidate, type ValidateProps } from "@/lib/validate";
import { useTranslation } from "react-i18next";
import Error from "@/components/custom-ui/error";
import { useForgot, useVerifyForgot } from "@/hooks/use-forgot";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  ForgotSchema,
  type ForgotFormData,
  VerifyForgotSchema,
  type VerifyForgotFormData,
} from "@/schemas/forgot";

export default function Forgot() {
  const [, setCaptchaId] = useState("");

  const v = useRouterQueryParam("validate");
  const isValidate = !!v;
  const validateParse = parseValidate(v || "");
  const { t } = useTranslation();
  const { forgot, isForgoting } = useForgot();
  const { verifyForgot, isVerifingForgot } = useVerifyForgot();

  // 根据验证状态创建不同的表单
  const form = useForm<ForgotFormData | VerifyForgotFormData>({
    resolver: zodResolver(isValidate ? VerifyForgotSchema() : ForgotSchema()),
    defaultValues: {
      email: isValidate ? (validateParse as ValidateProps)?.email || "" : "",
      captcha: "",
      captcha_id: "",
      ...(isValidate && {
        password: "",
        token: (validateParse as ValidateProps)?.token || "",
      }),
    },
  });

  if (v && !validateParse) {
    return <Error statusCode={400} message={t("Invalid validate")} />;
  }

  const onSubmit = (data: ForgotFormData | VerifyForgotFormData) => {
    const forgotParams = {
      email: (data as ForgotFormData).email,
      captcha: (data as ForgotFormData).captcha,
      captcha_id: (data as ForgotFormData).captcha_id,
    };
    if (!isValidate) {
      // 调用忘记密码接口
      forgot(forgotParams);
    } else {
      verifyForgot({
        ...forgotParams,
        password: (data as VerifyForgotFormData).password,
        token: (data as VerifyForgotFormData).token,
      });
    }
  };

  return (
    <div className="flex items-center justify-center py-12">
      <Card className="w-full min-w-xs max-w-md border border-white/20">
        <CardHeader className="text-center">
          <FormHead
            title={isValidate ? "Reset Password" : ""}
            description={isValidate ? "Set your new password." : ""}
          />
        </CardHeader>
        <CardContent>
          <Form {...form}>
            <form
              onSubmit={form.handleSubmit(onSubmit)}
              className="space-y-4"
              noValidate
            >
              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t("Email", { defaultValue: "Email" })}
                    </FormLabel>
                    <FormControl>
                      <Input
                        type="email"
                        placeholder={t("Enter email", {
                          defaultValue: "Enter email",
                        })}
                        startIcon={<Mail className="h-4 w-4" />}
                        disabled={isValidate}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {isValidate ? (
                <FormField
                  control={form.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>
                        {t("New Password", { defaultValue: "New Password" })}
                      </FormLabel>
                      <FormControl>
                        <PasswordInput
                          placeholder={t("Enter new password", {
                            defaultValue: "Enter new password",
                          })}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              ) : null}

              {isValidate ? (
                <FormField
                  control={form.control}
                  name="token"
                  render={({ field }) => (
                    <FormItem className="hidden">
                      <FormControl>
                        <Input type="hidden" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              ) : null}

              <FormField
                control={form.control}
                name="captcha"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t("Captcha", { defaultValue: "Captcha" })}
                    </FormLabel>
                    <FormControl>
                      <CaptchaInput
                        placeholder={t("Enter captcha code", {
                          defaultValue: "Enter captcha code",
                        })}
                        onCaptchaIdChange={(captchaId) => {
                          setCaptchaId(captchaId);
                          form.setValue("captcha_id", captchaId);
                        }}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {isValidate ? (
                <Button
                  className="w-full hover:cursor-pointer"
                  size="lg"
                  type="submit"
                  disabled={isVerifingForgot}
                >
                  {isVerifingForgot
                    ? t("Resetting...", { defaultValue: "Resetting..." })
                    : t("Reset Password", { defaultValue: "Reset Password" })}
                </Button>
              ) : (
                <Button
                  className="w-full hover:cursor-pointer"
                  size="lg"
                  type="submit"
                  disabled={isForgoting}
                >
                  {isForgoting
                    ? t("Sending...", { defaultValue: "Sending..." })
                    : t("Send Reset Link", { defaultValue: "Send Reset Link" })}
                </Button>
              )}
            </form>
          </Form>

          <div className="text-center space-y-2 mt-4">
            <div className="text-sm">
              <Link to="/cas/login" className="text-blue-600 hover:underline">
                {t("Back to Sign In", { defaultValue: "Back to Sign In" })}
              </Link>
            </div>
            <div className="text-sm">
              <Link to="/cas" className="text-gray-600 hover:underline">
                {t("Back to Home", { defaultValue: "Back to Home" })}
              </Link>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
